<template>
  <TopHeaderNav></TopHeaderNav>
  <div class="content-wrapper">
    <div class="page-content">
      <el-row>
        <el-col :offset="5" :span="11" style="padding: 10px;">
          <div class="article-page" v-loading="articleLoading">
            <div class="article-head">
              <h1 v-html="article.title"></h1>
              <div class="article-head-info">
                <i class="el-icon-time"></i> 创建日期 {{Utils.formatDate(article.createTime,'yyyy-MM-dd hh')}}<small>H</small>&nbsp;&nbsp;&nbsp;&nbsp;
                <i class="el-icon-chat-dot-square"></i> <strong class="fa-big fc-light">{{article.commentCount}}</strong> 条评论&nbsp;&nbsp;&nbsp;&nbsp;
                <i class="el-icon-view"></i> <strong class="fa-big fc-light">{{article.viewCount}}</strong> 次浏览&nbsp;&nbsp;&nbsp;&nbsp;
                <i class="el-icon-thumb"></i> <strong class="fa-big fc-light">{{article.thumbCount}}</strong> 个点赞&nbsp;&nbsp;&nbsp;&nbsp;
              </div>
              <el-divider></el-divider>
            </div>
            <div class="article-body" v-html="article.content">
            </div>
            <div class="article-footer">
              <el-button id="articleThumbBtn" v-if="article.thumbed" type="danger" icon="el-icon-thumb" round @click="toggleArticleThumb">取消点赞</el-button>
              <el-button id="articleThumbBtn" v-else type="danger" icon="el-icon-thumb" round plain @click="toggleArticleThumb">点 赞</el-button>
            </div>
            <div class="article-comment">
              <h1>留下点什么<el-tooltip effect="dark" content="本站采用 cookie 记住用户，在您第一次评论或留言时即视为您已同意本站使用 cookie 记住您的用户信息。" placement="top-start"><i class="el-icon-info color-warning"></i></el-tooltip>
              </h1>
              <div class="comment-form px-10" id="articleCommentBox"></div>
              <el-divider></el-divider>
              <h1>评论列表</h1>
              <div class="comment-list" v-loading="commentLoading">
                <template v-if="commentPageResult&&commentPageResult.records&&commentPageResult.records.length > 0" v-for="comment in commentPageResult.records" :key="comment">
                  <div class="comment-item">
                    <div class="user-face">
                      <div v-if="comment.commentator!=null&&comment.commentator.avatarUrl" class="avatar" style="background: none;">
                        <img :src="comment.commentator.avatarUrl" />
                      </div>
                      <div v-else class="avatar">
                      </div>
                    </div>
                    <div class="comment-con">
                      <div class="user" v-html="comment.commentator?comment.commentator.name:'\<small class=\'text-muted\'\>'+comment.commentIp+'\</small\>'"></div>
                      <div class="comment-text" v-html="comment.commentContent"></div>
                      <div class="comment-info">
                        <i class="el-icon-time"></i> {{Utils.formatDate(comment.createTime,'yyyy-MM-dd hh:mm')}} &nbsp;&nbsp;
                        <i class="el-icon-thumb" :class="{thumbed : comment.thumbed}" @click="toggleCommentThumb(comment.id)" :id="'thumb_comment_'+comment.id">&nbsp;{{comment.thumbCount}}</i>
                        <a href="javascript:;" @click="replyComment(comment)" class="reply-btn">回复</a>
                      </div>
                      <div class="comment-form reply-box" :id="'reply_'+comment.id" style="height:0;"></div>
                    </div>
                    <template v-if="comment.replyList&&comment.replyList.length > 0">
                      <div class="reply-list">
                        <div class="reply-item" v-for="reply in comment.replyList" :key="reply">
                          <div class="user-face">
                            <div v-if="reply.commentator!=null&&reply.commentator.avatarUrl" class="avatar" style="background: none;">
                              <img :src="reply.commentator.avatarUrl" />
                            </div>
                            <div v-else class="avatar">
                            </div>
                          </div>
                          <div class="reply-con">
                            <div class="user" v-html="reply.commentator?reply.commentator.name:'\<span class=\'text-muted\'\>'+reply.commentIp+'\</span\>'">
                            </div>
                            <small class="ml-5" v-if="reply.parentComment!=null">回复 @{{reply.parentComment.commentator?reply.parentComment.commentator.name:reply.parentComment.commentIp}}</small>
                            <div class="reply-text" v-html="reply.commentContent"></div>
                            <div class="reply-info">
                              <i class="el-icon-time"></i> {{Utils.formatDate(reply.createTime,'yyyy-MM-dd hh:mm')}} &nbsp;&nbsp;
                              <i class="el-icon-thumb" :class="{thumbed : reply.thumbed}" @click="toggleCommentThumb(reply.id)" :id="'thumb_comment_'+reply.id">&nbsp;{{reply.thumbCount}}</i>
                              <a href="javascript:;" @click="replyComment(reply)" class="reply-btn">
                                回复
                              </a>
                            </div>
                            <div class="comment-form reply-box" :id="'reply_'+reply.id" style="height:0;"></div>
                          </div>
                        </div>
                        <div class="load-more" :id="'loadMoreHolder_'+comment.id" @click="loadMoreReply(comment)" :hasMore="comment.hasMoreReply" :curPage="comment.curReplyPage">
                          <template v-if="comment.hasMoreReply">
                            <i class="el-icon-caret-bottom"></i>
                            <span class="load-more-text">&nbsp;&nbsp;更多回复</span>
                          </template>
                          <template v-else>
                            <span class="no-more-text">没有更多了</span>
                          </template>
                        </div>
                      </div>
                    </template>
                  </div>
                </template>
                <el-empty v-else description="还没有人评论哦~赶紧来抢沙发吧">
                </el-empty>
                <template v-if="!inLoadingMore&&hasMoreArticleComment">
                  <div class="load-more">
                    向下滚动加载更多
                  </div>
                </template>
                <template v-if="inLoadingMore&&hasMoreArticleComment">
                  <div class="load-more mt-10">
                    <i class="el-icon-loading"></i> 正在加载...
                  </div>
                </template>
                <template v-if="!hasMoreArticleComment">
                  <div class="load-more disabled">
                    <span class="no-more-text">已经到底啦...</span>
                  </div>
                </template>
              </div>
            </div>
          </div>
        </el-col>
        <el-col :span="3" style="padding-top: 10px;">
          <el-affix :offset="60">
            <div id="articleNavHolder" class="article-nav-holder">
              <div class="nav-title">目录</div>
              <el-tree :data="articleNavMenu" node-key="id" @node-click="navAction" :indent="5" accordion highlight-current ref="navTree" />
            </div>
          </el-affix>
        </el-col>
      </el-row>
    </div>
  </div>
</template>
<script>
  import TopHeaderNav from '@/components/TopHeaderNav'
  import CommentBox from '@/components/comment/CommentBox'
  import articleRender from '@/plugins/ArticleRender'
  import goTop from '@/plugins/GoTop'
  import { createApp, h } from 'vue'

  export default {
    components: {
      TopHeaderNav,
      CommentBox,
      articleRender
    },
    data() {
      let articleId = this.$route.params.articleId;
      this.$axios.get('/api/article-service/article/' + articleId).then(resultData => {
        this.article = resultData;
        setTimeout(() => {
          this.articleLoading = false;
        }, 1000);
        this.$nextTick(function () {
          articleRender.init({
            navTree: this.$refs.navTree
          }); // 初始化文章页面控件
          this.loadCommentBox("articleCommentBox"); // 加载评论组件到文章评论表单
          this.loadingArticleComments(); // 加载评论列表
          goTop.init();
          // 设置滚动加载
          let loadMoreArticleComments = this.loadMoreArticleComments;
          $(window).scroll(function () {
            let scrollTop = $(this).scrollTop();
            let scrollHeight = $(document).height();
            let windowHeight = $(this).height();
            if (scrollTop + windowHeight >= (scrollHeight - 10)) {
              setTimeout(() => {
                loadMoreArticleComments();
              }, 300);
            }
          })
        })
      });
      return {
        articleLoading: true,
        commentLoading: true,
        inLoadingMore: false,
        hasMoreArticleComment: true,
        article: {},
        commentPageResult: {},
        articleNavMenu: [],
        navAction: articleRender.navAction
      }
    },
    methods: {
      loadingArticleComments() {
        let articleId = this.article.id;
        this.$axios.get('/api/comment-service/comment/pageByQuery', {
          articleId: articleId
        }).then(resultData => {
          this.commentPageResult = resultData;
          setTimeout(() => {
            this.commentLoading = false;
          }, 1000);
        });
      },
      loadMoreArticleComments() {
        if (!this.inLoadingMore && this.hasMoreArticleComment && this.commentPageResult.current) {
          this.inLoadingMore = true;
          let articleId = this.article.id;
          let pageNum = this.commentPageResult.current + 1;
          this.$axios.get('/api/comment-service/comment/pageByQuery', {
            articleId: articleId,
            current: pageNum
          }).then(resultData => {
            this.inLoadingMore = false;
            this.commentPageResult.current = resultData.current;
            this.commentPageResult.total = resultData.total;
            this.commentPageResult.size = resultData.size;
            this.hasMoreArticleComment = resultData.total > (resultData.size * resultData.current)
            resultData.records.forEach((item, index) => {
              this.commentPageResult.records.push(item);
            })
          });
        }
      },
      // 在指定 dom 中加载评论组件 replyComment 若是回复评论则传入当前回复的评论对象
      loadCommentBox(domId, replyComment) {
        let articleId = this.article.id;
        const commentSubmitCallBack = this.commentSubmitCallBack;
        const replySubmitCallBack = this.replySubmitCallBack;
        let commentApp = createApp({
          render() {
            return h(CommentBox, {
              domId: domId,
              articleId: articleId,
              replyComment: replyComment ? replyComment : {},
              commentSubmitCallBack: commentSubmitCallBack,
              replySubmitCallBack: replySubmitCallBack
            });
          }
        }).mount("#" + domId);
      },
      commentSubmitCallBack(domId, commentId) {
        // 文章评论成功回调
        if (domId) {
          this.loadCommentBox(domId);
        }
        this.loadingArticleComments(commentId);
      },
      replySubmitCallBack(domId, comment, replyComment) {
        // 回复成功回调
        if (domId) {
          $('#' + domId).css('heihgt', '0').empty();
        }
        this.loadingArticleComments(comment.id);
      },
      replyComment(comment) {
        let commentId = comment.id;
        $('.reply-box').css('height', '0');
        $("#reply_" + commentId).css('height', '280px');
        this.loadCommentBox('reply_' + commentId, comment);
      },
      toggleCommentThumb(commentId) {
        let $thumbIcon = $('#thumb_comment_' + commentId);
        const resetIcon = ($thumbIcon) => {
          $thumbIcon.removeClass('disabled').find('i.el-icon-loading').remove();
        }
        $thumbIcon.addClass('disabled').append('&nbsp;<i class="el-icon-loading"></i>');
        this.$axios.postParamsWithObj('/api/comment-service/comment/toggleComment', {
          commentId: commentId
        }).then((result) => {
          setTimeout(() => {
            let count = parseInt($thumbIcon.text().trim());
            count = count + result;
            $thumbIcon.html('&nbsp;' + count);
            if (result > 0) {
              $thumbIcon.addClass('thumbed');
            } else if (result < 0) {
              $thumbIcon.removeClass('thumbed');
            }
            resetIcon($thumbIcon);
          }, 1000);
        }).catch(() => {
          resetIcon($thumbIcon);
        });
      },
      loadMoreReply(comment) {
        if (comment.hasMoreReply) {
          let $loadHolder = $("#loadMoreHolder_" + comment.id);
          $loadHolder.addClass("disabled")
            .find('i.el-icon-caret-bottom').hide()
            .find('span.load-more-text').hide();
          $loadHolder.append('<span class="loading-wrapper">&nbsp;<i class="el-icon-loading"></i>&nbsp;加载中...</span>');
          let pageNum = comment.curReplyPage ? comment.curReplyPage + 1 : 2;
          this.$axios.get('/api/comment-service/comment/pageCommentReply', {
            commentId: comment.id,
            pageNum: pageNum
          }).then((replyList) => {
            replyList.forEach((item, index) => {
              comment.replyList.push(item);
            });
            comment.curReplyPage = pageNum;
            setTimeout(() => {
              if (replyList.length < 3) {
                comment.hasMoreReply = false;
              }
              $loadHolder.removeClass("disabled")
                .find('i.el-icon-caret-bottom').show()
                .find('span.load-more-text').show();
              $loadHolder.find('span.loading-wrapper').remove();
            }, 1000);
          }).catch(() => {});
        }
      },
      toggleArticleThumb() {
        let articleId = this.article.id;
        $('#articleThumbBtn').append('<span class="loading-wrapper">&nbsp;<i class="el-icon-loading"></i>').addClass('disabled');
        const resetBtn = () => {
          $('#articleThumbBtn').removeClass('disabled').find('.loading-wrapper').remove();
        }
        this.$axios.postParamsWithObj('/api/article-service/article/toggleThumb', {
          articleId: articleId
        }).then((change) => {
          setTimeout(() => {
            this.article.thumbCount += change;
            if (change > 0) {
              this.article.thumbed = true;
            } else {
              this.article.thumbed = false;
            }
            resetBtn();
          }, 1000);
        }).catch(() => {
          resetBtn();
        })
      }
    }
  }
</script>